import axios from "axios";
import { ref } from "vue";
const apikey = ref("");
const applicationId = ref("");
const sessionId = ref("");

// 获取应用信息
export const getApplicationInfo = async (apiKey: string) => {
  try {
    const response = await axios.get(
      "https://riscqa.hsk.top/api/application/profile",
      {
        headers: {
          Authorization: `${apiKey}` // 传递 apiKey 在请求头中
        }
      }
    );
    // console.log("123",response.data.data.work_flow.nodes[0].properties);
    applicationId.value = response.data.data.id;
    return response.data.data.work_flow.nodes[0].properties; // 返回请求结果
  } catch (error) {
    console.error("请求失败:", error);
    throw error; // 抛出错误
  }
};

export const getSessionId = async () => {

  // 从 localStorage 获取数据
  const mkParameters = localStorage.getItem('MKparameters');
  // 如果数据存在且是有效的 JSON 字符串
  if (mkParameters) {
    try {
      // 解析 JSON 数据
      const parsedData = JSON.parse(mkParameters);

      // 获取 apiKey
      apikey.value = parsedData[0]?.apiKey;
      // console.log(apikey.value); // 输出 apiKey 的值
    } catch (error) {
      console.error('解析 MKparameters 时出错:', error);
    }
  }
  try {
    const response = await axios.get(
      "https://riscqa.hsk.top/api/application/"+ applicationId.value +"/chat/open",
      {
        headers: {
          Authorization: `${ apikey.value}` // 传递 apiKey 在请求头中
        }
      }
    );
    sessionId.value = response.data.data;
    return response.data.data// 返回请求结果
  } catch (error) {
    console.error("请求失败:", error);
    throw error; // 抛出错误
  }
};

// 获取应用参数信息
export const getParameters = async (apiKey: string) => {
  try {
    const response = await axios.get("https://riscbase.hsk.top/v1/parameters", {
      headers: {
        Authorization: `Bearer ${apiKey}` // 使用 apiKey 作为 Authorization 的值
      }
    });
    return response.data; // 返回参数数据
  } catch (error) {
    console.error("请求参数失败:", error);
    throw error;
  }
};

//发送消息
export async function postMessage(messageData: {}) {
  try {
    const response = await axios.post(
      "https://riscqa.hsk.top/api/application/chat_message/" + sessionId.value,
      messageData,
      {
        headers: {
          Authorization: `${ apikey.value}` // 传递 apiKey 在请求头中
        }
      }
    );
    const responseData = response.data;
    console.log("123",responseData);
  } catch (error) {
    console.error("Error:", error);
  }
}
